<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import {
  processTableData,
  filterValidSampleAdatas,
  splitDataIntoPages,
  getHeaders,
} from "@/utils/method";
import { useAnalysetStore } from "@/store/index.ts";
import AnalyesAPI from "@/api/system/analyes.ts";
import FluorideB from "@/components/analysisSheetComponents/soil/tmpl87/index.vue";
import Device from "@/components/analysisSheetComponents/component/Device.vue";
// 复制粘贴
import Index from "@/components/analysisSheetComponents/component/index.vue";
import indexPdf from "@/components/analysisSheetComponents/soil/tmpl87/indexPdf.vue";

var options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      name: "", // 工作表名称
      color: "", // 工作表颜色
      index: 0, // 工作表索引
      status: 1, // 激活状态
      order: 0, // 工作表的下标
      column: 10, // 列数
      defaultRowHeight: 30, // 自定义行高
      defaultColWidth: 100, // 自定义列宽
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "样品编号" }, // A1
        { r: 0, c: 1, v: "类型" }, // A1
        { r: 0, c: 2, v: "样品量m(g)" }, // B1
        { r: 0, c: 3, v: "干物质Wdm(%)" }, // B1
        { r: 0, c: 4, v: "待测物" }, // B1
        { r: 0, c: 5, v: "检出限(mg/kg)" }, // B1
        { r: 0, c: 6, v: "试样含量ρ (μg/mL)" }, // B1
        { r: 0, c: 7, v: "样品含量ω(mg/kg)" }, // B1
        { r: 0, c: 8, v: "测定结果" }, // B1
        { r: 0, c: 9, v: "备注" }, // B1
      ], // 初始化数据
      config: {
        merge: {}, // 合并单元格
        columnlen: {
          // 设置列宽
          0: 130, // 第一列宽度 150px
          1: 130,
          2: 130,
          3: 130,
          4: 120,
          5: 130,
          6: 130,
          7: 120,
          8: 120,
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([{ table: "仪器名称", id: 1 }]);
const waterForm = ref({
  bdatas: {
    cdtj: {},
    rypz: {},
    jzqxpz: {},
    unnamed: [
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
      {
        un_xh: "",
        un_dcw: "",
        un_jzqx: "",
        un_xh2: "",
        un_dcw2: "",
        un_jzqx2: "",
      },
    ],
    // b_bzlmjc: [],
  },
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
});
const processedData = ref([]);

const cdatas = ref([]);
const switchAB = ref(true);
const switchAdd = ref(true);
const sheetData = ref("");
const jsonData = ref(null);
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
const checkTime = ref("");
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 调用 Luckysheet 内建方法添加行
  //   获取表单信息
  getWaterCapacity();
  getMethod();
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
    ? analyseStatusPage.waterForm.tableItem.test_method
    : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  waterForm.value.category_id =
    analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};

// 点击保存
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || "默认字段",
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = filterValidSampleAdatas(processTableData(data));

  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }

  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: record_sn,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then((data) => {
    console.log("调接口拿数据", data);
    ElMessage.success("保存成功！");
    // getWaterCapacity();
    switchAdd.value = false;
  });
};

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // record_sn: record_sn,
    record_sn: record_sn,
  };
  AnalyesAPI.getAnalyseACapacity(josn).then((data) => {
    if (!Array.isArray(data) || data.length !== 0) {
      console.log("获取水质容量 A单", data);
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      waterForm.value.bdatas =
        Array.isArray(data.bdatas) && data.bdatas.length === 0
          ? {}
          : data.bdatas;
      // cdtj
      waterForm.value.bdatas.cdtj =
        Array.isArray(data.bdatas.cdtj) && data.bdatas.cdtj.length === 0
          ? {}
          : data.bdatas.cdtj;
      processedData.value = data.adatas;
      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 40);

      tabler.value = getHeaders(data.adatas, 23);
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      };
    }
  });
};

// 用于获取最新的表格数据
const getUpdatedData = () => {
  if (jsonData.value === null) {
    sheetData.value = luckysheet.getLuckysheetfile();
  } else {
    sheetData.value = jsonData.value.sheets[0];
  }
  // const data = formatLuckysheetData(sheetData.value)
  // console.log(data)
  const tableDataString = JSON.stringify(sheetData.value); // 将表格数据转为 JSON 字符串
  localStorage.setItem("tableData", tableDataString);
  console.log(sheetData.value); // 打印当前表格的数据
};

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files;
  console.log(files);
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }
  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != "xlsx") {
    alert("Currently only supports the import of xlsx files");
    return;
  }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson.sheets);
      jsonData.value = exportJson;

      luckysheet.destroy();
      luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value;
};
// 下载
const downloadDetail = async () => {
  // console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage && switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">
          土壤 气相色谱质谱法分析原始记录（A面）
        </h1>
        <div>SXLPHJ/JL/CX-22-87</div>
        <table class="table">
          <tr>
            <td colspan="1">任务编号</td>
            <td colspan="7">
              <el-input
                v-model="waterForm.task_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1">采样日期</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.sampling_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="1">分析方法</td>
            <td colspan="7">
              <el-input
                v-model="waterForm.method"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1">分析日期</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.anal_time"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="1">环境温度</td>
            <td colspan="6" style="width: 7%">
              <el-input
                v-model="waterForm.temperature"
                style="width: 100%; border: 1px solid transparent"
                placeholder=""
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    ℃
                  </span>
                </template>
              </el-input>
            </td>
            <td colspan="1">环境湿度</td>
            <td colspan="9">
              <el-input
                v-model="waterForm.humidity"
                style="width: 100%; border: 1px solid transparent"
                placeholder=""
              >
                <template #append>
                  <span style="background-color: transparent; color: black">
                    ℃
                  </span>
                </template>
              </el-input>
            </td>
          </tr>
          <!-- <tr>
            <td colspan="1">分析仪器</td>
            <td colspan="5" style="width: 7%">
              <el-input
                v-model="waterForm.device_name"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1">仪器型号</td>
            <td colspan="1">
              <el-input
                v-model="waterForm.device_model"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1">仪器编号</td>
            <td colspan="8">
              <el-input
                v-model="waterForm.device_number"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr> -->
          <Device :water-form="waterForm" :colspan="5" />
          <tr>
            <td colspan="1" rowspan="3">测定条件</td>
            <td colspan="16" style="width: 7%">
              <el-input
                v-model="waterForm.bdatas.cdtj.cd_1"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="16" style="width: 7%">
              <el-input
                v-model="waterForm.bdatas.cdtj.cd_2"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="16" style="width: 7%">
              <el-input
                v-model="waterForm.bdatas.cdtj.cd_3"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="1">计算公式</td>
            <td colspan="7">
              <el-input
                v-model="waterForm.js_formula"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
            <td colspan="1">试样定容体积Vx（mL）</td>
            <td colspan="5">
              <el-input
                v-model="waterForm.sydrtj"
                style="width: 100%; border: 1px solid transparent"
                placeholder="请输入"
              />
            </td>
          </tr>
          <tr>
            <td colspan="1">备注</td>
            <td colspan="15">
              <el-input
                v-model="waterForm.notes"
                style="width: 150px; border: 1px solid transparent"
              />
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
      </el-card>
    </div>
    <div v-show="!switchAB">
      <FluorideB :waterForm="waterForm" />
    </div>
    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :check-time="checkTime"
        :switch="true"
        :switch-a-b="switchAB"
        :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
        :download-detail="downloadDetail"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
